package com.zl.codereview.util;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.zl.codereview.MyTextGutterIconRenderer;
import com.zl.codereview.git.GitService;
import com.zl.codereview.review.ReviewConstant;
import com.zl.codereview.util.ObjectUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.UUID;

public class IdeaUtils {

    private static GitService gitService = GitService.getInstance();

    public static String codeReviewPath(AnActionEvent e){
        //模块路径
        String modulePath = IdeaUtils.getModuleFilePath(e);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/","-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName+".ser";
    }

    public static String codeReviewPath(Project project,VirtualFile virtualFile){
        //模块路径
        String modulePath = IdeaUtils.getModuleFilePath(project,virtualFile);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/","-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName+".ser";
    }

    public static String codeReviewPath(Module module){
        //模块路径
        String modulePath = IdeaUtils.getModulePath(module);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/","-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName+".ser";
    }

    public static String getModulePath(Module module) {
        VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
        // 假设一个模块只有一个内容根目录，你可以根据实际需求选择合适的目录
        if (contentRoots.length > 0) {
            return contentRoots[0].getPath();
        } else {
            return null; // 或者抛出异常，表明没有找到内容根目录
        }
    }

    public static String getModuleFilePath(AnActionEvent e){
        Project project = e.getProject();
        if(!ObjectUtils.isEmpty(project)) {
            Module module = e.getData(LangDataKeys.MODULE);
            if (!ObjectUtils.isEmpty(module)) {
                return ModuleRootManager.getInstance(module).getContentRoots()[0].getPath();
            }else{
                return ProjectRootManager.getInstance(project).getContentRoots()[0].getPath();
            }
        }
        JOptionPaneUtils.warn("找不到项目或模块");
        throw new RuntimeException("找不到项目或模块");
    }


    public static String getModuleFilePath(Project project,VirtualFile virtualFile) {
        Module module = ModuleUtil.findModuleForFile(virtualFile, project);
        if (!ObjectUtils.isEmpty(module)) {
            return ModuleRootManager.getInstance(module).getContentRoots()[0].getPath();
        }else{
            return ProjectRootManager.getInstance(project).getContentRoots()[0].getPath();
        }
    }

    public static String uuid(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }


    @SuppressWarnings("unchecked")
    public static<T> T parseObject(String name){
        try (FileInputStream fileIn = new FileInputStream(name)) {
            ObjectInputStream in = new ObjectInputStream(fileIn);

            // 读取对象并打印信息
            return (T)in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void writeObject(Object obj,String name){
        File file = new File(name);
        if(file.exists()){
            file.delete();
        }
        try (FileOutputStream fileOut = new FileOutputStream(name)){
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            // 将对象序列化为字节流并写入文件
            out.writeObject(obj);
            System.out.println("Person object serialized and written to the file.");
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static String createDir(String path) {
        File file = new File(path);
        if (!file.exists() && file.mkdir()) {
            return path;
        }
        return "";
    }


    public static void addGutterIcon(Project project,String content, int lineNumber,int status) {
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null) {
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (psiFile != null) {
                MarkupModel markupModel = editor.getMarkupModel();
                Document document = editor.getDocument();
                RangeHighlighter[] allHighlighters = markupModel.getAllHighlighters();
                for(RangeHighlighter highlighter :  allHighlighters){
                    int nowLine = document.getLineNumber(highlighter.getStartOffset());
                    GutterIconRenderer gutterIconRenderer = highlighter.getGutterIconRenderer();
                    if(lineNumber - 1 == nowLine && gutterIconRenderer instanceof MyTextGutterIconRenderer){
                        markupModel.removeHighlighter(highlighter);
                    }
                }
                RangeHighlighter highlighter = markupModel.addLineHighlighter(lineNumber - 1, 0, null);
                // 设置行高亮标记的 gutter 图标渲染器
                MyTextGutterIconRenderer renderer = new MyTextGutterIconRenderer("R",content, status, lineNumber);
                highlighter.setGutterIconRenderer(renderer);


            }
        }
    }
}
